﻿// src/crudOption/message/notificationList.js

/**
 * 运维通知（NOTICE）列表 actions（仅用 hasAuth）
 *
 * 用法（页面 setup）：
 *
 *   import { createBuildNotificationActions } from '@/crudOption/message/notificationList'
 *
 *   const buildRowActions = createBuildNotificationActions({
 *
 *     fns: { openEditDialog, confirmHide, confirmShow, confirmSend, confirmResend, loadDel },
 *     denyStrategy: 'hide',  // 或 'disable'
 *   })
 *
 *   // <ActionBar :row="row" :max-inline="3" :actions="buildRowActions" />
 */

// ===== 业务状态规范化（与页面一致） =====
const U = s => String(s ?? "").toUpperCase();

function normSendStatus(raw) {
  const s = U(raw);
  if (!s) return "INIT"; // 空按未发送
  if (s === "PROCESS") return "PROCESSING";
  if (s === "UNSENT") return "INIT";
  return s; // INIT / PROCESSING / SUCCESS / FAIL
}

function normShowStatus(raw) {
  const s = U(raw);
  if (s === "SHOWING") return "SHOW";
  if (s === "HIDDEN") return "HIDE";
  return s || "HIDE"; // 默认按隐藏
}

// ===== 语义判定 =====
const isUnsent = row => normSendStatus(row.status) === "INIT";
const isProcess = row => normSendStatus(row.status) === "PROCESSING";
const isSuccess = row => normSendStatus(row.status) === "SUCCESS";
const isFail = row => normSendStatus(row.status) === "FAIL";

const isShowing = row => normShowStatus(row.showStatus) === "SHOW";
const isHidden = row => normShowStatus(row.showStatus) === "HIDE";

// ===== 只用 hasAuth 做权限判断 =====
/**
 * @param {(keys:string[])=>boolean} hasAuth
 * @param {string|string[]|function|null|undefined} perm
 * @param {object} row
 */
function allowByPerm(hasAuth, perm, row) {
  if (!perm) return true;
  if (typeof perm === "function") {
    try {
      return !!perm(row);
    } catch {
      return false;
    }
  }
  const keys = Array.isArray(perm) ? perm : [perm];
  return typeof hasAuth === "function" ? !!hasAuth(keys) : false;
}

/** 未授权处理：'hide'（默认）或 'disable'（置灰） */
function applyDenyStrategy(action, denyStrategy) {
  if (denyStrategy === "disable") {
    return { ...action, disabled: true, onClick: undefined, danger: false, divided: false };
  }
  return null;
}

// 核心：解析 hasAuth（支持注入；没传则尝试从 Pinia 获取）
function resolveHasAuth(passedHasAuth) {
  if (passedHasAuth) return passedHasAuth;
  try {
    const user = useUserInfoStore(); // ⚠️ 必须在 setup() 或激活的 Pinia 上下文里调用
    return user.hasAuth; // getters 返回的就是 (keys)=>boolean
  } catch (e) {
    console.warn("[notificationList] hasAuth 未传且 Pinia 未激活，默认视为无权限");
    return () => false;
  }
}

/**
 * 工厂：注入 hasAuth + 回调，返回 (row)=>actions
 * @param {object} opts
 *  - hasAuth: (keys:string[])=>boolean 非必传：Pinia 的 hasAuth
 *  - fns: { openEditDialog, confirmHide, confirmShow, confirmSend, confirmResend, loadDel }
 *  - denyStrategy?: 'hide'|'disable'
 */
export function createBuildNotificationActions(opts = {}) {
  const hasAuth = resolveHasAuth(opts.hasAuth);
  const fns = opts.fns || {};
  const denyStrategy = opts.denyStrategy === "disable" ? "disable" : "hide";

  return function buildRowActions(row) {
    // 仅 SUCCESS 才有显隐按钮
    const showHideEnabled = isSuccess(row);

    const candidates = [
      // 编辑（常驻）
      {
        key: "edit",
        label: "编辑",
        order: 1,
        when: true,
        perm: PERMS.MESSAGE.NOTICE.UPDATE,
        onClick: () => fns.openEditDialog?.(row),
      },

      // 隐藏 / 展示（仅 SUCCESS）
      {
        key: "hide",
        label: "隐藏",
        order: 2,
        when: showHideEnabled && isShowing(row),
        perm: PERMS.MESSAGE.NOTICE.ENABLE,
        onClick: () => fns.confirmHide?.(row),
      },

      {
        key: "show",
        label: "展示",
        order: 3,
        when: showHideEnabled && isHidden(row),
        perm: PERMS.MESSAGE.NOTICE.ENABLE,
        onClick: () => fns.confirmShow?.(row),
      },

      // 发送（仅未发送）
      {
        key: "send",
        label: "发送",
        order: 4,
        when: isUnsent(row),
        perm: PERMS.MESSAGE.NOTICE.SEND,
        onClick: () => fns.confirmSend?.(row),
      },

      // 重发（仅失败）
      {
        key: "resend",
        label: "重新发送",
        order: 5,
        when: isFail(row),
        // type: "danger",
        // danger: true, // 行内按钮红色；下拉项加红色样式
        perm: PERMS.MESSAGE.NOTICE.SEND,
        onClick: () => fns.confirmResend?.(row),
      },

      // 删除（常驻）
      {
        key: "del",
        label: "删除",
        order: 99,
        when: true,
        type: "info",
        perm: PERMS.MESSAGE.NOTICE.DELETE,
        onClick: () => fns.loadDel?.(row),
      },
    ];

    const seen = new Set();
    const result = [];

    for (const a of candidates) {
      if (!a || !a.when) continue;
      const pass = allowByPerm(hasAuth, a.perm, row);
      const finalAction = pass ? a : applyDenyStrategy(a, denyStrategy);
      if (!finalAction) continue;
      if (seen.has(finalAction.key)) continue;
      seen.add(finalAction.key);
      result.push(finalAction);
    }

    result.sort((x, y) => (x.order ?? 0) - (y.order ?? 0));
    return result;
  };
}

/** 一次性生成（可选） */
export function buildNotificationActions(row, options = {}) {
  return createBuildNotificationActions(options)(row);
}

export default createBuildNotificationActions;
